import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to flutter',
      theme: ThemeData(primaryColor: Colors.amberAccent),
      home: RandomWord(),
    );
  }
}

class RandomWord extends StatefulWidget {
  @override
  _RandomWordState createState() => _RandomWordState();
}

class _RandomWordState extends State<RandomWord> {
  final wordPair = WordPair.random();

  final _sugesstions = <WordPair>[];
  final _saved = Set<WordPair>();

  final _biggerFont = const TextStyle(fontSize: 18.0);

// 有状态的组件 需要 shift + r 重启应用
  @override
  Widget build(BuildContext context) {
    //return Text(wordPair.asPascalCase);
    return Scaffold(
      appBar: AppBar(
        title: Text('Startup Name Generator'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.list),
            onPressed: _pushSaved,
          ),
        ],
      ),
      body: _buildSuggestions(),
    );
  }

  void _pushSaved() {
    print("who press me");

    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) {
        final tiles = _saved.map((pair) {
          return ListTile(
            title: Text(
              pair.asPascalCase,
              style: _biggerFont,
            ),
            // 颜色会变为主题颜色
            selected: true,
          );
        });

        final divided = ListTile.divideTiles(
          context: context,
          tiles: tiles,
        ).toList();

        return Scaffold(
          appBar: AppBar(
            title: Text('Saved Suggestions'),
          ),
          body: ListView(
            children: divided,
          ),
        );
      }),
    );
  }

  Widget _buildSuggestions() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return Divider(); // 1像素的分割线

        final index = i ~/ 2; // 取整
        if (index >= _sugesstions.length) {
          // 如果是建议列表中最后一个单词对

          // 接着再生成10个单词对，然后添加到建议列表
          _sugesstions.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_sugesstions[index]);
      },
    );
  }

  Widget _buildRow(WordPair pair) {
    // 判断是否收藏
    final alreadySaved = _saved.contains(pair);

    return ListTile(
      title: Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }
}
